package wangjg.security.core.validator;

import java.util.Set;

import wangjg.security.core.AuthoritySet;

/**
 * 验证用户是否有访问资源的权限
 * @author wangjg
 *
 */
public class AuthorityValidator /* implements ResourceValidator */{

	public static boolean validate(Object resource, Object user) {
		
		if(user instanceof AuthoritySet){
			Set userAuthorities=((AuthoritySet)user).getAuthorities();
			if(resource instanceof AuthoritySet == false){
				return false;
			}
			Set resourceAuthorities = ((AuthoritySet)resource).getAuthorities();
			if(checkAuthority(userAuthorities, resourceAuthorities)){
				return true;
			}
		}
		
		return false;
	}

	public static boolean checkAuthority(final Set userAuthorities ,final Set resourceAuthorities){
		if(userAuthorities==null || userAuthorities.size()==0){
			return false;
		}
		
		if(resourceAuthorities==null || resourceAuthorities.size()==0){
			return false;
		}
		
		//check
		for(Object resourceAuthority : resourceAuthorities){
			if(userAuthorities.contains(resourceAuthority)){
				return true;
			}
		}
		
		//Authority of Authority
		for(Object userAuthority : userAuthorities){
			if(userAuthority instanceof AuthoritySet){
				Set uaas = ((AuthoritySet)userAuthority).getAuthorities();
				if(checkAuthority(uaas ,resourceAuthorities)){
					return true;
				}
			}
		}
		return false;
	}

}
